<?php

namespace plugin\ky_shouyin\app\middleware;
use ReflectionClass;
use ReflectionException;
use support\exception\BusinessException;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AuthMiddleware  implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        // TODO: Implement process() method.
        if ($request->method() == 'OPTIONS') {
            return $this->cors($request, response(''));
        }

        $controller = $request->controller;
        $action = $request->action;
        $loginUserId = session('user.id') ?? session('user.uid');


        // 禁用账户不允许post请求
        if ($request->post()) {

        }

        // 路由是匿名函数或者用户已经登录的走正常流程
        if (!$controller || $loginUserId) {
            if ($loginUserId && $controller === 'AccountController' && $action === 'userlogin') {
                return $this->cors($request, redirect('/app/ky_shouyin/admin/index'));
            }
            return $this->cors($request, $handler($request));
        }
        // 获取控制器鉴权信息
        $class = new ReflectionClass($controller);
        $properties = $class->getDefaultProperties();
        // 获取需要登陆的控制器action
        $noNeedLogin = $properties['noNeedLogin'] ?? [];
        // 需要登录
        if (!in_array($action, $noNeedLogin)) {
            $msg = '请登录';
            if ($request->expectsJson()) {
                return $this->cors($request, json(['code' => -1, 'msg' => $msg, 'data' => [], 'error' => ['message' => $msg]]));
            }
            return $this->cors($request, redirect('/app/ky_shouyin/admin/account/userlogin?redirect=' . urlencode($request->uri())));
        }
        return $this->cors($request, $handler($request));
    }
    /**
     * 跨域headers
     *
     * @param \Webman\Http\Request $request
     * @param \Webman\Http\Response $response
     * @return Response
     */
    protected function cors(Request $request, Response $response)
    {
        if (method_exists($response, 'exception') && $exception = $response->exception()) {
            $code = $exception->getCode() ?: 1;
            $msg = $exception->getMessage();
            $response = $request->expectsJson() ? json([
                'code' => $code,
                'msg' => $msg,
                'error' => ['message' => $msg],
                'data' => [],
                'traces' => config('plugin.ky_shouyin.app.debug') ? $exception->getTraceAsString() : ''
            ]) : $response;
        }
        return $response->withHeaders([
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Origin' => $request->header('origin', '*'),
            'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
            'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
        ]);
    }


}